package cn.iocoder.yudao.module.picturebook.service.classes;

import cn.iocoder.yudao.module.picturebook.controller.admin.classmember.vo.ClassMemberSaveReqVO;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.classmember.ClassMemberDO;
import cn.iocoder.yudao.module.picturebook.service.classmember.ClassMemberService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import cn.iocoder.yudao.module.picturebook.controller.admin.classes.vo.*;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.classes.ClassesDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.picturebook.dal.mysql.classes.ClassesMapper;

import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;

/**
 * 班级信息 Service 实现类
 *
 * @author 芋道源码
 */
@Slf4j
@Service
@Validated
public class ClassesServiceImpl implements ClassesService {

    @Resource
    private ClassesMapper classesMapper;
    @Resource
    private ClassMemberService classMemberService;

    // ... existing code ...
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long createClasses(ClassesSaveReqVO createReqVO) {
        // 参数校验
        if (createReqVO == null) {
            return null;
        }

        if (createReqVO.getTeacherId() == null || createReqVO.getTeacherId() <= 0) {
            return null;
        }

        if (createReqVO.getTeacherName() == null || createReqVO.getTeacherName().trim().isEmpty()) {
            return null;
        }

        if (createReqVO.getClassName() == null || createReqVO.getClassName().trim().isEmpty()) {
            return null;
        }

        try {
            //同一个老师不能创建同一个名字的班级
            List<ClassesDO> existingClasses = classesMapper.getByTeacherId(createReqVO.getTeacherId());
            if (existingClasses != null) {
                //判断是否有相同的名字
                for (ClassesDO existingClass : existingClasses) {
                    if (existingClass != null && createReqVO.getClassName().equals(existingClass.getClassName())) {
                        return null;
                    }
                }
            }

            // 生成班级邀请码（纯数字8位）
            String classCode;
            QueryWrapper<ClassesDO> queryWrapper = new QueryWrapper<>();
            int retryCount = 0;
            final int MAX_RETRY = 10;

            do {
                classCode = String.format("%08d", new Random().nextInt(99999999));
                queryWrapper.clear(); // 清除旧条件
                queryWrapper.eq("class_code", classCode);
                retryCount++;

                if (retryCount > MAX_RETRY) {
                    return null;
                }
            } while (classesMapper.selectOne(queryWrapper) != null);

            // 设置班级邀请码
            createReqVO.setClassCode(classCode);

            // 插入班级信息
            ClassesDO classes = BeanUtils.toBean(createReqVO, ClassesDO.class);
            int insertResult = classesMapper.insert(classes);
            if (insertResult != 1) {
                return null;
            }

            // 插入班级成员（教师）
            ClassMemberSaveReqVO classMemberSaveReqVO = new ClassMemberSaveReqVO();
            classMemberSaveReqVO.setMemberName(createReqVO.getTeacherName());
            classMemberSaveReqVO.setUserId(createReqVO.getTeacherId());
            classMemberSaveReqVO.setClassId(classes.getId());
            classMemberSaveReqVO.setRole(2); // 教师角色

            classMemberService.createClassMember(classMemberSaveReqVO);

            return classes.getId();
        } catch (Exception e) {
            return null;
        }
    }


    @Override
    public void updateClasses(ClassesSaveReqVO updateReqVO) {
        // 参数校验
        if (updateReqVO == null) {
            return;
        }
        if (updateReqVO.getId() == null) {
            return;
        }

        // 校验存在
        if (classesMapper.selectById(updateReqVO.getId()) == null) {
            return;
        }

        try {
            //先根据班级id查询现在的老师
            ClassesDO classes = classesMapper.selectById(updateReqVO.getId());
            // 更新
            ClassesDO updateObj = BeanUtils.toBean(updateReqVO, ClassesDO.class);
            //如果更改的信息中含有班级的userid
            if (updateObj.getTeacherId() != null && classes.getTeacherId() != null) {
                //则先将原本班级成员角色换为学生，现在换为老师
                classMemberService.updateClassMemberRole(classes.getTeacherId(), updateObj.getId(), 1);
                //将班级的userid改为老师
                classMemberService.updateClassMemberRole(updateObj.getTeacherId(), updateObj.getId(), 2);
            }
            classesMapper.updateById(updateObj);
        } catch (Exception e) {
            // 记录日志但不中断流程
            log.error("[updateClasses][updateReqVO({}) 更新失败]", updateReqVO, e);
        }
    }

    @Override
    public void deleteClasses(Long id) {
        // 参数校验
        if (id == null) {
            return;
        }

        // 校验存在
        if (classesMapper.selectById(id) == null) {
            return;
        }
        // 删除
        classesMapper.DeleteById(id);
    }

    @Override
    public void deleteClassesListByIds(List<Long> ids) {
        // 参数校验
        if (ids == null || ids.isEmpty()) {
            return;
        }

        // 删除
        classesMapper.deleteByIds(ids);
    }


    private void validateClassesExists(Long id) {
        // 参数校验
        if (id == null) {
            return;
        }

        if (classesMapper.selectById(id) == null) {
            log.error("[getClasses][id({}) 不存在]", id);
            // 不抛出异常，仅记录日志
            return;
        }
    }

    @Override
    public ClassesRespVO getClasses(Long id) {
        // 参数校验
        if (id == null) {
            return null;
        }

        ClassesDO classesDO = classesMapper.selectById(id);
        if (classesDO == null) {
            return null;
        }

        try {
            //根据teacherId去查询老师名称
            String teacherName = classMemberService.getMemberName(classesDO.getTeacherId(), classesDO.getId());
            ClassesRespVO classesRespVO = new ClassesRespVO().setTeacherName(teacherName);
            return BeanUtils.toBean(classesDO, ClassesRespVO.class).setTeacherName(classesRespVO.getTeacherName());
        } catch (Exception e) {
            // 出现异常时返回不带教师名称的班级信息
            return BeanUtils.toBean(classesDO, ClassesRespVO.class);
        }
    }

    @Override
    public PageResult<ClassesDO> getClassesPage(ClassesPageReqVO pageReqVO) {
        // 参数校验
        if (pageReqVO == null) {
            return PageResult.empty();
        }

        return classesMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ClassesAllRespVO> getAllClass(Integer userId) {
        List<ClassesAllRespVO> result = new ArrayList<>();

        // 参数校验
        if (userId == null) {
            return result;
        }

        try {
            // 获取用户所属的班级成员信息
            List<ClassMemberDO> memberList = classMemberService.getClassByUser(userId);
            if (memberList == null || memberList.isEmpty()) {
                return result;
            }

            // 提取班级ID列表
            List<Long> classIdList = convertList(memberList, ClassMemberDO::getClassId);
            if (classIdList.isEmpty()) {
                return result;
            }

            // 根据班级ID查询班级信息
            List<ClassesDO> classList = classesMapper.selectList(new QueryWrapper<ClassesDO>().in("id", classIdList));
            if (classList == null || classList.isEmpty()) {
                return result;
            }

            // 初始化结果列表容量
            result = new ArrayList<>(classList.size());

            // 组装返回结果
            Long userIdLong = userId.longValue();
            for (ClassesDO classesDO : classList) {
                if (classesDO != null) {
                    ClassesAllRespVO vo = new ClassesAllRespVO();
                    vo.setId(classesDO.getId());
                    vo.setClassName(classesDO.getClassName());
                    vo.setTeacherId(classesDO.getTeacherId());
                    vo.setClassCode(classesDO.getClassCode());
                    vo.setStatus(classesDO.getStatus());
                    vo.setCreateTime(classesDO.getCreateTime());
                    vo.setRole(determineUserRole(classesDO.getTeacherId(), userIdLong));
                    result.add(vo);
                }
            }
        } catch (Exception e) {
            // 出现异常时返回空列表
            return new ArrayList<>();
        }

        return result;
    }

    /**
     * 判断用户在班级中的角色
     */
    private int determineUserRole(Long teacherId, Long userId) {
        if (teacherId == null || userId == null) {
            return 1; // 默认为学生角色
        }
        return Objects.equals(teacherId, userId) ? 2 : 1;
    }


    @Override
    public ClassesDO queryClassesByClassCode(String classCode) {
        // 参数校验
        if (classCode == null || classCode.trim().isEmpty()) {
            return null;
        }

        return classesMapper.queryClassesByClassCode(classCode);
    }

}